<!-- 新增访视计划 -->
<template>
  <div>
    <a-modal
      width="80%"
      :title="modalTitle"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <!-- 行内编辑table start -->
      <a-table
        bordered
        :loading="tableLoading"
        :columns="columns"
        :dataSource="data"
        :pagination="false"
        size="small">
        <template
          v-for="(col, i) in ['name', 'stage', 'rangeTime', 'windowPeriod', 'address']"
          :slot="col"
          slot-scope="text, record"
        >
          <a-input
            :key="col"
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            :placeholder="columns[i].title"
            @change="(e) => handleInputChange(e.target.value, record.key, col)"
          />
          <template v-else>{{ text }}</template>
        </template>
        <template slot="operation" slot-scope="text, record">
          <template v-if="record.editable">
            <span v-if="record.isNew">
              <a @click="saveRow(record)">添加</a>
              <a-divider type="vertical" />
              <a-popconfirm title="是否要删除此行？" @confirm="remove(record.key)">
                <a>删除</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a @click="saveRow(record)">保存</a>
              <a-divider type="vertical" />
              <a @click="cancel(record.key)">取消</a>
            </span>
          </template>
          <span v-else>
            <a @click="toggle(record.key)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm title="是否要删除此行？" @confirm="remove(record.key)">
              <a>删除</a>
            </a-popconfirm>
          </span>
        </template>
      </a-table>
      <a-button block style="margin-top: 20px" type="dashed" icon="plus" @click="newRow">新增访视计划</a-button>
      <!-- 行内编辑table end -->
    </a-modal>
  </div>
</template>

<script>
import monitor from '@/utils/monitor'
import addVisitModal from '@/monitor/views/overview/detail/responsible/components/visit/addVisitModal.js'
const watch = monitor(addVisitModal)
export default {
  name: 'AddVisitModel',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    modalTitle: {
      type: String,
      default: ''
    },
    recordId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      isEdit: false,
      confirmLoading: false,
      tableLoading: false,
      columns: [
        {
          title: '*访视名词',
          dataIndex: 'name',
          key: 'name',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '*访视阶段',
          dataIndex: 'stage',
          key: 'stage',
          scopedSlots: { customRender: 'stage' }
        },
        {
          title: '距离基线或随机时间',
          dataIndex: 'rangeTime',
          key: 'rangeTime',
          scopedSlots: { customRender: 'rangeTime' }
        },
        {
          title: '访视窗',
          dataIndex: 'windowPeriod',
          key: 'windowPeriod',
          scopedSlots: { customRender: 'windowPeriod' }
        },
        {
          title: '访视地点',
          dataIndex: 'address',
          key: 'address',
          scopedSlots: { customRender: 'address' }
        },
        {
          title: '操作',
          key: 'operation',
          // fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      data: [

      ]
    }
  },
  methods: watch({
    // 新增行
    newRow () {
      const length = this.data.length
      this.data.push({
        key: length === 0 ? '1' : (parseInt(this.data[length - 1].key) + 1).toString(),
        name: '',
        stage: '',
        rangeTime: '',
        windowPeriod: '',
        address: '',
        editable: true,
        isNew: true
      })
    },
    // 删除行
    remove (key) {
      const newData = this.data.filter((item) => item.key !== key)
      this.data = newData
    },
    // 行状态切换
    toggle (key) {
      const target = this.data.find((item) => item.key === key)
      target._originalData = { ...target }
      target.editable = !target.editable
      console.log(this.data)
      this.$forceUpdate()
    },
    // input输入事件
    handleInputChange (value, key, column) {
      const newData = [...this.data]
      const target = newData.find((item) => key === item.key)
      if (target) {
        target[column] = value
        this.data = newData
      }
    },
    // 取消事件，还原原本行数据
    cancel (key) {
      const target = this.data.find((item) => item.key === key)
      Object.keys(target).forEach((key) => {
        target[key] = target._originalData[key]
      })
      target._originalData = undefined
    },
    // row保存
    saveRow (record) {
      this.tableLoading = true
      const { name, stage, key } = record // 需要校验的必填字段
      // const { name, stage, rangeTime, windowPeriod, address, key } = record // 需要校验的必填字段
      // if (!name || !stage || !rangeTime || !windowPeriod || !address) {
      if ((name === undefined || name === null || name === '') || (stage === undefined || stage === null || stage === '')) {
        this.tableLoading = false
        this.$message.error('访视名词和访视阶段为必填项')
        return
      }
      // 模拟网络请求、卡顿 100ms, 不需要走接口，去掉即可
      new Promise((resolve) => {
        setTimeout(() => {
          resolve({ loop: false })
        }, 100)
      }).then(() => {
        const target = this.data.find((item) => item.key === key)
        delete target._originalData // 删除克隆字段，防止编辑出现该部分
        // 上面一行最后的“key”是否应为“record.key”?
        target.editable = false
        target.isNew = false
        this.tableLoading = false
      })
    },
    handleOk () {
      if (!this.checkMessage()) {
        return false
      }
      this.addVisit()
      console.log('ok', this.data)
      this.data.forEach(item => { // 清除多余字段
        delete item.editable
        delete item.isNew
        delete item.key
        delete item.id
      })
      this.$emit('ok', JSON.stringify(this.data))
    },
    handleCancel () {
      console.log('handleCancel')
      this.$emit('cancel')
    },
    // 校验表格所有信息是否填写完整
    checkMessage () {
      if (this.data.length === 0) {
        this.$message.error('计划数量不得为空')
        return false
      }
      const target = this.data.find(item => item.editable === true)
      if (target) {
        this.$message.error('请将所有数据先进行保存再提交')
        return false
      }
      return true
    },
    // 新增访视埋点
    addVisit () {}
  })
}
</script>
<style scoped lang="scss">
</style>
